//JavaScript代码区域
layui.use(['element', 'table', 'jquery', 'laydate', 'form'], function () {
    var element = layui.element;
    var table = layui.table;
    var laydate = layui.laydate;
    var form = layui.form;
    $(function () {
        tableRender();
        form.render();
    });

    function tableRender() {
        table.render({
            elem: '#role_table'
            // , height: 312
            ,
            url: LOCALHOSTURL + '/role/getRoles' //数据接口
            ,
            method: "get",
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,
                statusCode: 200 //规定成功的状态码，默认：0
            },
            page: true //开启分页
            ,
            title: "角色表",
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [ //表头
                    {
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                    field: 'id',
                    title: 'ID',
                    sort: true,
                    width: 60
                }, {
                    field: 'name',
                    title: '角色名',
                    templet: function (res) {
                        if (res.name == null)
                            return '暂无';
                        return res.name;
                    }
                }, {
                    field: 'description',
                    title: '描述',
                    templet: function (res) {
                        if (res.description == null)
                            return '暂无';
                        return res.description;
                    }
                }, {
                    field: 'userCount',
                    title: '用户数',
                    templet: function (res) {
                        if (res.userCount == null)
                            return 0;
                        return res.userCount;
                    }
                }, {
                    fixed: 'right',
                    title: '操作',
                    toolbar: '#barDemo',
                    width: 150
                }
                ]
            ],
            done: function (res) {
                console.log(res.data);
                sessionStorage.setItem("role", JSON.stringify(res.data));
            }
        });
    }

    table.on('toolbar(demo)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                layer.open({
                    type: 2,
                    title: "添加角色",
                    area: ['100%', '100%'],
                    content: ["edit_role.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                        body.find("#update").html("添加");
                        body.find("#update").click(function () {
                            let code = body.find("#code").val();
                            let name = body.find("#name").val();
                            let desc = body.find("#desc").val();
                            if (code == '') {
                                layer.msg("角色编码不能为空", function () {
                                    body.find("#code").focus();
                                })
                            } else if (name == '') {
                                layer.msg("角色名不能为空", function () {
                                    body.find("#name").focus();
                                })
                            } else {
                                let roledata = {
                                    "code": code,
                                    "name": name,
                                    "description": desc
                                };
                                console.log(roledata);
                                let result = ajaxModel("/role/addRole", "post", roledata);
                                if (result.code == 200) {
                                    layer.alert(result.message, {icon: 1});
                                    tableRender();
                                    layer.close(index);

                                } else
                                    layer.alert(result.message, {icon: 1});
                            }
                        });
                        body.find("#cancel").click(function () {
                            layer.close(index);
                        });
                    }
                });
                break;
        }
        ;
    })
    ;

//监听行工具事件
    table.on('tool(demo)', function (obj) {
        var data = obj.data;
        console.log(data);
        if (obj.event === 'auz') {
            layer.open({
                type: 2,
                title: "角色权限管理",
                area: ['100%', '100%'],
                content: ["authority.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    // var iframeWindow = layero.find('iframe')[0].contentWindow;
                    // iframeWin.auzTransfer();
                    let roleId = data.id;//得到角色id
                    //获取所有的权限集合
                    let result = myAjax("/permission/getAllPermissions", "get");
                    let allPermission = result.data;//得到所有权限
                    let allPermissionIds = [];
                    $.each(allPermission, function (key, val) {
                        allPermissionIds.push(val.id);//取得所有权限的id值
                    });
                    //获取角色所拥有的可用权限
                    let rolePermission = data.permissions;
                    let rolePermissionIds = [];
                    //获取角色所拥有的可用权限id
                    $.each(rolePermission, function (key, val) {
                        rolePermissionIds.push(val.id);//取得所有权限的id值
                    });
                    //获取角色暂未拥有的可用权限id=
                    // 所有权限id-已拥有的权限id=
                    // 未拥有的权限id+已拥有的权限id值-已拥有的权限id
                    let roleNoPermissionIds = allPermissionIds.filter(function (item) {
                        return rolePermissionIds.indexOf(item) == -1;
                    })
                    let left = [];
                    let right = [];
                    console.log("allPermission");
                    console.log(allPermission);
                    console.log("allPermissionIds");
                    console.log(allPermissionIds);
                    console.log("rolePermissionIds");
                    console.log(rolePermissionIds);
                    console.log("roleNoPermissionIds");
                    console.log(roleNoPermissionIds);
                    let transfer = iframeWin.layui.transfer;
                    console.log(transfer);
                    transfer.render({
                        elem : body.find("#authority"),
                        title: ["所有权限", "已有权限"],
                        data: allPermission,
                        parseData: function (res) {
                            return {
                                "value": res.id,
                                "title": res.name
                            };
                        },
                        value: rolePermissionIds,
                        showSearch: true,
                        onchange: function (data, index) {
                            console.log(data); //得到当前被穿梭的数据
                            console.log(index); //如果数据来自左边，index 为 0，否则为 1
                            let dataIds = [];
                            //将移动的数据的id提取出来
                            $.each(data, function (key, val) {
                                dataIds.push(val.value);
                            });
                            if (index == 0) {//如果数据来自左边，则将左边相同数据移除
                                // left = left.filter(function (item) {
                                //     return leftIds.indexOf(item) == -1;
                                // });
                                left = left.filter(function (item) {
                                    return dataIds.indexOf(item) == -1;
                                });
                                //将移除的数据加入右边
                                $.each(dataIds, function (key, val) {
                                    right.push(val);
                                });
                                right = right.filter(function (item) {
                                    return rolePermissionIds.indexOf(item) == -1;
                                });
                            } else if (index == 1) {//如果数据来自右边，则将右边相同数据移除
                                // right = right.filter(function (item) {
                                //     return rightIds.indexOf(item) == -1;
                                // });
                                right = right.filter(function (item) {
                                    return dataIds.indexOf(item) == -1;
                                });
                                //将移动的数据加入到左边
                                $.each(dataIds, function (key, val) {
                                    left.push(val);
                                });
                                left = left.filter(function (item) {
                                    return roleNoPermissionIds.indexOf(item) == -1;
                                });
                            }
                            console.log("left");
                            console.log(left);
                            console.log("right");
                            console.log(right);
                            console.log("leftIds");
                            console.log(roleNoPermissionIds);
                            console.log("rightIds");
                            console.log(rolePermissionIds);
                        }
                    });
                    body.find("#save").click(function () {
                        //获得右侧数据
                        // let getData = iframeWin.layui.transfer.getData('team');
                        // console.log(getData);
                        let datas = {
                            "left": JSON.stringify(left),
                            "right": JSON.stringify(right),
                            "roleId": roleId
                        }
                        let result = myAjax("/rolePermission/updateRolePermission", "post", datas);
                        if (result) {
                            layer.alert(result.message, {icon: 1});
                            layer.close(index);
                            tableRender();
                        } else
                            layer.alert(result.message);

                    });
                    body.find(("#cancel")).click(function () {
                        layer.close(index);
                    });
                }
            })
        } else if (obj.event === 'del') {
            layer.confirm("确定要删除" + data.name + "?", function (index) {
                // obj.del();
                let result = myAjax("/role/deleteRole", "get", {id: data.id});
                alert(result.message);
                tableRender();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            layer.open({
                type: 2,
                title: "修改角色",
                area: ['100%', '100%'],
                content: ["edit_role.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    body.find("#code").val(data.code);
                    body.find("#name").val(data.name);
                    body.find("#desc").val(data.description);
                    body.find("#update").click(function () {
                        let code = body.find("#code").val();
                        let name = body.find("#name").val();
                        let desc = body.find("#desc").val();
                        if (code == '') {
                            layer.msg("角色编号不能为空", function () {
                                body.find("#code").focus();
                            })
                        } else if (name == '') {
                            layer.msg("角色名不能为空", function () {
                                body.find("#name").focus();
                            })
                        } else {
                            // let result = myAjax("/permission/checkPermission", "get", {"username": code});
                            // if (result.data == null) {
                            let roledata = {
                                "id": data.id,
                                "code": code,
                                "name": name,
                                "description": desc
                            };
                            console.log(roledata);
                            let result = ajaxModel("/role/updateRole", "post", roledata);
                            if (result.code == 200) {
                                layer.alert(result.message, {icon: 1});
                                tableRender();
                                layer.close(index);

                            } else
                                layer.alert(result.message, {icon: 1});
                        }
                    });
                    body.find("#cancel").click(function () {
                        layer.close(index);
                    });
                    iframeWin.layui.form.render();
                }
            });
        }
    })
})
;
